import time

import wtforms
from wtforms.validators import Email, Length, EqualTo, InputRequired, ValidationError, NumberRange
from werkzeug.security import check_password_hash
from web.models.boke_models import User
from flask import session


class RegisterForms(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='邮箱格式不正确！')])
    code = wtforms.StringField(validators=[Length(min=5, max=5, message='验证码格式不正确！')])
    username = wtforms.StringField(validators=[Length(min=1, max=8, message='用户名格式不正确!')])
    password = wtforms.StringField(validators=[Length(min=3, max=20, message='密码格式不正确!')])
    password_confirm = wtforms.StringField(EqualTo('password', message='两次输入密码不相同!'))

    def validate_code(self, field):
        try:
            print(session['code'])
            code = session['code'].split('-')[0]
            tt = session['code'].split('-')[1]
            print(code, tt)
            if (float(time.time()) - float(tt) > 300) or (str(code) != str(field.data)):
                raise ValidationError('验证码错误！')
        except:
            raise ValidationError('验证码错误！')


class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='邮箱格式不正确！')])
    password = wtforms.StringField()
    code = wtforms.StringField()

    # def validate_password(self, field):
    #
    #     user = User.query.filter_by(email=self.email.data).first()
    #     print(str(field.data))
    #
    #     if (not user) or (not check_password_hash(user.password, field.data)):
    #         raise ValidationError("密码错误!")

    def validate_code(self, field):
        try:
            print(session['vcode'])
            code = session['vcode'].split('-')[0]
            print(code)
            if str(code).lower() != str(field.data).lower():
                raise ValidationError('验证码错误！')
        except:
            raise ValidationError('验证码错误！')


class QuestionForm(wtforms.Form):
    title = wtforms.StringField(validators=[Length(min=3, max=100, message="标题格式错误！")])
    content = wtforms.StringField(validators=[Length(min=3, message="内容格式错误！")])
    detail = wtforms.StringField(validators=[Length(min=3, message="内容格式错误！")])


class AnswerForm(wtforms.Form):
    content = wtforms.StringField(validators=[Length(min=1, message="内容格式错误！")])
